<template>
	<tl-sub-page :render="render" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" width="1200px" @open="open" @close="close">
		<el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
			<el-row>
				<el-col :span="12">
					<el-form-item label="一级部门" prop="deptcommoncode" :rules="rules.validateRequire">
						<el-select v-model="model.deptcommoncode" :disabled="!isBspOperator" filterable clearable>
							<el-option v-for="item in codeModel.deptcommoncodeList" :key="item.id" :label="item.name" :value="item.code" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="区域名称" prop="name" :rules="rules.validateRequire">
						<el-input v-model="model.name" @blur="saveName($event)"></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="区域级别" prop="arealevel" :rules="rules.validateRequire">
						<el-select v-model="model.arealevel" filterable clearable :disabled="!isBspOperator">
							<el-option v-for="item in codeModel.arealevelList" :key="item.code" :label="item.name" :value="item.code" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="单位类型" prop="areatype" :rules="rules.validateRequire">
						<el-select v-model="model.areatype" filterable clearable @change="areatypeChange">
							<el-option v-for="item in codeModel.areatypeList" :key="item.code" :label="item.name" :value="item.code" />
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="上级区域" prop="parentid" v-show="isBspOperator">
						<tl-ref-area-group v-model="model.parentid" :initDisplayData.sync="model.parentname" :singleSelect="true" :queryParam="model.deptcommoncode" :queryDataUrl="url.queryDataUrl" :queryTreeUrl="url.queryTreeUrl"> </tl-ref-area-group>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="上级区域" prop="parentname" v-show="!isBspOperator">
						<el-input v-model="model.parentname" disabled></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="区域授权人员" prop="areaauthorizationusercode" :rules="rules.validateRequire">
						<tl-ref-user v-model="model.areaauthorizationusercode" :initDisplayData.sync="model.areaauthorizationusername" dataType="code" :singleSelect="false"></tl-ref-user>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="生效日期" prop="pmsenableddate" :rules="model.useful === '1' ? { required: false } : rules.validateRequire" v-if="this.isAdd">
						<el-date-picker :picker-options="dateOptions" v-model="model.pmsenableddate" type="month" placeholder="选择生效月份" :disabled="disablePmsDate" value-format="yyyy-MM-dd HH:mm:ss"> </el-date-picker>
					</el-form-item>
					<el-form class="tl-form" ref="form1" :model="model" :rules="rules" label-width="150px" v-if="!this.isAdd">
						<el-form-item label="生效日期" prop="pmsenableddate" :rules="model.useful === '1' ? { required: false } : rules.validateRequire">
							<el-date-picker :picker-options="dateOptions" v-model="model.pmsenableddate" type="month" placeholder="选择生效月份" :disabled="disablePmsDate" value-format="yyyy-MM-dd HH:mm:ss"> </el-date-picker>
						</el-form-item>
					</el-form>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="24">
					<el-form-item label="备注" prop="description">
						<el-input v-model="model.description" type="textarea" :rows="3"></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="排序码" prop="sortcode">
						<el-input-number v-model="model.sortcode" controls-position="right" :step="1" :min="0" style="width:100%"></el-input-number>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<tl-approval-history ref="history" sourceType="MmsProvinceCityMatchinfo" :sourceId="model.id" />
		<div slot="footer" class="dialog-footer">
			<el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-if="disableEditSubmit === false && !disableSave" :disabled="disableSave">保存</el-button>
			<el-button type="primary" @click="validateAndApproval" v-show="changeUseful && !stateApproval" :loading="submitLoading"><svg-icon icon-class="send" />{{ actionName }}</el-button>
			<el-button type="primary" @click="$refs.history.visible = true" v-show="stateApproval"><svg-icon icon-class="list" />审批历史</el-button>
		</div>
	</tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
/** 子组件 */
import tlRefAreaGroup from './refAreaGroup'
import { MMS_AREA_LEVEL } from '@/const/const'
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
	mixins: [mixin_approval_edit],
	components: { tlRefAreaGroup },
	data() {
		return {
			moduleTitle: '省份地市信息',
			urlPrefix: '/mms/provinceCityMatchinfo/',
			url: {
				// 额外的url
				queryDataUrl: '/mms/provinceCityMatchinfo/list',
				queryTreeUrl: '/mms/provinceCityMatchinfo/queryParentTreeList',
				flipUseful: '/mms/provinceCityMatchinfo/flipUseful'
			},
			dateOptions: {
				disabledDate: function(date) {
					return date < new Date()
				}
			},
			isInCharge: false,
			changeUseful: false
		}
	},
	props: {
		cityInCharge: {
			type: Array,
			default: () => []
		},
		isBspOperator: {
			type: Boolean,
			default: false
		},
		isCfoOrPm: {
			type: Boolean,
			default: false
		},
		userLevel: {
			type: String,
			default: ''
		},
		dataParam: {
			type: Object,
			default: undefined
		},
        BSPOperatorParam: {
            type: Object,
			default: null
        }
	},
	computed: {
		// 审批状态判断
		stateApproval() {
			return this.model.state === 1
		},
		actionName() {
			return this.model.useful === '1' ? '禁用' : '启用'
		},
		disablePmsDate() {
			return (!this.changeUseful && !this.isAdd) || this.stateApproval || this.model.useful === '1'
		}
	},
	methods: {
		assignDefaultValue() {
			if (this.isAdd) {
				this.$set(this.model, 'orgcode', this.org.code)
				this.$set(this.model, 'disporgcode', this.org.name)
				this.$set(this.model, 'deptcode', this.dept.code)
				this.$set(this.model, 'deptname', this.dept.fullname)
				this.$set(this.model, 'usercode', this.user.code)
				this.$set(this.model, 'username', this.user.name)
			}
		},
		// 校验单位类型
		areatypeChange() {
			if (!this.model.arealevel) {
				this.model.areatype = ''
				this.$tap.alert('请先选择区域级别!')
			}
			// 省直属单位的区域级别必须为市级
			if (this.model.arealevel !== MMS_AREA_LEVEL.city && this.model.areatype === '2') {
				this.model.areatype = ''
				this.$tap.alert('当前区域级别不为“市”，单位类型不允许选择“省直属单位”!')
			}
			// 市直属单位的区域级别必须为县级
			if (this.model.arealevel !== MMS_AREA_LEVEL.country && this.model.areatype === '1') {
				this.model.areatype = ''
				this.$tap.alert('当前区域级别不为“县”，单位类型不允许选择“省直属单位”!')
			}
		},
		loaded() {
			// 页面加载完毕执行
			if (this.isAdd) {
				if (!this.isBspOperator) {
					this.codeModel.areatypeList = this.codeModel.areatypeList.filter(item => item.name !== '市直属单位')
					this.$set(this.model, 'arealevel', MMS_AREA_LEVEL.province)
					this.$set(this.model, 'deptcommoncode', this.dataParam.deptCommonCode)
					this.$set(this.model, 'parentid', '10' + this.dataParam.deptCommonCode)
					this.$set(this.model, 'parentname', this.dataParam.deptCommonName)
				} else {
                    this.BSPOperatorParam.BSPOperatorDept && this.$set(this.model, 'deptcommoncode', '' + this.BSPOperatorParam.BSPOperatorDept)
					this.BSPOperatorParam.BSPOperatorPID && this.$set(this.model, 'parentid', '' + this.BSPOperatorParam.BSPOperatorPID)
					this.BSPOperatorParam.BSPOperatorPName && this.$set(this.model, 'parentname', '' + this.BSPOperatorParam.BSPOperatorPName)
                }
			}
			// 去除所有表单校验
			let forms = Object.entries(this.$refs).filter(comobj => Object.hasOwn(comobj[1], 'validate'))
			for (let i = 0; i < forms.length; i++) {
					forms[i][1].clearValidate()
			}
		},
		saveName(event) {
			let namelist = this.codeModel.deptname2List
			let obj = {}
			obj = namelist.find(function(item) {
				return item.name === event.target.value
			})
			if (obj) {
				this.$set(this.model, 'code', obj.code)
				this.$set(this.model, 'namecode', obj.code)
			}
		},
		// 进行所有表单校验
		validateAllForm() {
			// 获取当前组件所有表单子组件
			let forms = Object.entries(this.$refs).filter(comobj => Object.hasOwn(comobj[1], 'validate'))
			return new Promise((resolve, reject) => {
				// 单个表单效验
				const doValidateOneForm = formRef => {
					return new Promise((resolve, reject) => {
						formRef.validate(valid => (valid ? resolve() : reject()))
					})
				}
				Promise.all(forms.map(formRef => doValidateOneForm(formRef[1])))
					.then(_ => {
						return resolve(true)
					})
					.catch(_ => {
						return reject('效验未通过')
					})
			})
		},
		// 校验并提交审批
		async validateAndApproval() {
			try {
				await this.validateAllForm()
				// 省总财总 运营人员直接保存
				if (this.isCfoOrPm || this.isBspOperator) {
					let param = {
						id: this.model.id,
						pmsenableddate: this.model.pmsenableddate
					}
					this.$tap.confirm('您确定要' + this.actionName + '该区域么').then(_ => {
						getAction(this.url.flipUseful, param).then(res => {
							if (!res.success) {
								this.$tap.alert(res.message)
							}
							this.queryData(this.model.id)
							this.$emit('refresh')
						})
					})
				} else {
					this.doSubmitApproval()
				}
			} catch (err) {}
		},
		// 提交审批前 需赋值  单据审批人
		beforeApproval() {
			this.model.usercode = this.$store.getters.user.code
			this.model.username = this.$store.getters.user.name
			this.model.deptcode = this.$store.getters.dept.code
			this.model.deptname = this.$store.getters.dept.deptoperfullname
			return true
		},
		// 清空打开dialog 变量赋值
		close() {
			this.changeUseful = false
			this.$emit('refresh')
		}
	}
}
</script>
